package com.goalias.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.goalias.constant.SystemConstants;
import com.goalias.domain.entity.Article;
import com.goalias.domain.entity.Tag;
import com.goalias.domain.vo.TagCountVo;
import com.goalias.mapper.ArticleMapper;
import com.goalias.mapper.TagMapper;
import com.goalias.resp.Result;
import com.goalias.service.IArticleService;
import com.goalias.service.ITagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 标签表 服务实现类
 * </p>
 *
 * @author goalias
 * @since 2024-12-12
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements ITagService {
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private TagMapper tagMapper;

    @Override
    public Result getTagCountList() {
        List<TagCountVo> tagCountList = articleMapper.getTagCountList();
        return Result.success(tagCountList);
    }

    @Override
    public Tag getOrAddTagByName(Long categoryId,String name) {
        LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tag::getName, name);
        Tag tag = getOne(wrapper);

        if (tag == null) {
            tag = new Tag();
            tag.setName(name);
            tag.setCategoryId(categoryId);
            save(tag);
        }
        return tag;
    }

    @Override
    public Result getTags(Long categoryId) {
        List<Tag> tags = new ArrayList<>();
        if (Objects.isNull(categoryId)){
            return Result.success(tags);
        }
        QueryWrapper<Tag> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", categoryId);
        wrapper.eq("del_flag", SystemConstants.ARTICLE_STATUS_NORMAL);
        tags = tagMapper.selectList(wrapper);
        return Result.success(tags);
    }
}
